--[[
Mana
This mod adds mana to players, a special attribute

License: MIT License
]]

--[===[
	Initialization
]===]

local S = minetest.get_translator("mana")

local store = minetest.get_mod_storage()

mana = {}
mana.playerlist = {}

mana.settings = {}
mana.settings.default_max = 200
mana.settings.default_regen = 1
mana.settings.regen_timer = 1.0

do
	local default_max = tonumber(minetest.settings:get("mana_default_max"))
	if default_max ~= nil then
		mana.settings.default_max = default_max
	end

	local default_regen = tonumber(minetest.settings:get("mana_default_regen"))
	if default_regen ~= nil then
		mana.settings.default_regen = default_regen
	end

	local regen_timer = tonumber(minetest.settings:get("mana_regen_timer"))
	if regen_timer ~= nil then
		mana.settings.regen_timer = regen_timer
	end
end


--[===[
	API functions
]===]

local function init_player(playername)
	local tab
	local savestring = store:get_string(playername)
	if savestring and savestring ~= "" then
		tab = minetest.deserialize(savestring)
	else
		tab = {}
	end
	mana.playerlist[playername] = tab

	tab.mana = tab.mana or 0
	tab.maxmana = tab.maxmana or mana.settings.default_max
	tab.regen = tab.regen or mana.settings.default_regen
	tab.remainder = tab.remainder or 0
	tab.tick_callbacks = {}

	if minetest.get_modpath("hudbars") ~= nil then
		local player = minetest.get_player_by_name(playername)
		hb.init_hudbar(player, "mana", mana.get(playername), mana.getmax(playername))
	else
		mana.hud_add(playername)
	end
end

function mana.set(playername, value)
	if not mana.playerlist[playername] then
		init_player(playername)
	end

	if value < 0 then
		minetest.log("info", "[mana] Warning: mana.set was called with negative value!")
		value = 0
	end
	value = mana.round(value)
	if value > mana.playerlist[playername].maxmana then
		value = mana.playerlist[playername].maxmana
	end
	if mana.playerlist[playername].mana ~= value then
		mana.playerlist[playername].mana = value
		mana.hud_update(playername)
	end
end

function mana.setmax(playername, value)
	if not mana.playerlist[playername] then
		init_player(playername)
	end

	if value < 0 then
		value = 0
		minetest.log("info", "[mana] Warning: mana.setmax was called with negative value!")
	end
	value = mana.round(value)
	if mana.playerlist[playername].maxmana ~= value then
		mana.playerlist[playername].maxmana = value
		if(mana.playerlist[playername].mana > value) then
			mana.playerlist[playername].mana = value
		end
		mana.hud_update(playername)
	end
end

function mana.setregen(playername, value)
	if not mana.playerlist[playername] then
		init_player(playername)
	end

	mana.playerlist[playername].regen = value
end

function mana.get(playername)
	if not mana.playerlist[playername] then
		init_player(playername)
	end

	return mana.playerlist[playername].mana
end

function mana.getmax(playername)
	if not mana.playerlist[playername] then
		init_player(playername)
	end

	return mana.playerlist[playername].maxmana
end

function mana.getregen(playername)
	if not mana.playerlist[playername] then
		init_player(playername)
	end

	return mana.playerlist[playername].regen
end

function mana.add_up_to(playername, value)
	local t = mana.playerlist[playername]

	if not t then
		init_player(playername)
	end

	value = mana.round(value)
	if(t ~= nil and value >= 0) then
		local excess
		if((t.mana + value) > t.maxmana) then
			excess = (t.mana + value) - t.maxmana
			t.mana = t.maxmana
		else
			excess = 0
			t.mana = t.mana + value
		end
		mana.hud_update(playername)
		return true, excess
	else
		return false
	end
end

function mana.add(playername, value)
	local t = mana.playerlist[playername]

	if not t then
		init_player(playername)
	end

	value = mana.round(value)
	if(t ~= nil and ((t.mana + value) <= t.maxmana) and value >= 0) then
		t.mana = t.mana + value
		mana.hud_update(playername)
		return true
	else
		return false
	end
end

function mana.subtract(playername, value)
	local t = mana.playerlist[playername]

	if not t then
		init_player(playername)
	end

	value = mana.round(value)
	if(t ~= nil and t.mana >= value and value >= 0) then
		t.mana = t.mana -value
		mana.hud_update(playername)
		return true
	else
		return false
	end
end

function mana.subtract_up_to(playername, value)
	local t = mana.playerlist[playername]

	if not t then
		init_player(playername)
	end

	local ovalue = value
	value = mana.round(value)
	if(t ~= nil and value >= 0) then
		local missing
		local actually
		if((t.mana - value) < 0) then
			missing = math.abs(t.mana - value)
			actually = t.mana
			t.mana = 0
		else
			missing = 0
			actually = value
			t.mana = t.mana - value
		end
		mana.hud_update(playername)
		return true, missing, actually
	else
		return false, ovalue, 0
	end
end

function mana.register_on_tick(identifier, playername, fun)
	assert(type(identifier) == "string")
	assert(type(playername) == "string")
	assert(type(fun) == "function")

	local tab = mana.playerlist[playername]

	if not tab then
		if minetest.get_player_by_name(playername) then
			init_player(playername)
			tab = mana.playerlist[playername]
			assert(tab)
		else
			return false
		end
	end

	local result = true
	if tab.tick_callbacks[identifier] then
		result = tab.tick_callbacks[identifier]
	end
	tab.tick_callbacks[identifier] = fun

	return result
end

function mana.unregister_on_tick(identifier, playername)
	local tab = mana.playerlist[playername]

	if not tab then
		return false
	end

	if tab.tick_callbacks[identifier] then
		tab.tick_callbacks[identifier] = nil
		return true
	else
		return false
	end
end

--[===[
	Loading data, saving data, setting up stuff for players.
]===]

function mana.save(playername)
	local dst = {}
	local src = mana.playerlist[playername]

	if not src then
		return false
	end

	dst.mana = src.mana
	dst.maxmana = src.maxmana
	dst.regen = src.regen
	dst.remainder = src.remainder

	local savestring = minetest.serialize(dst)

	store:set_string(playername, savestring)

	return true
end


minetest.register_on_respawnplayer(function(player)
	local playername = player:get_player_name()
	mana.set(playername, 0)
	mana.hud_update(playername)
end)


minetest.register_on_leaveplayer(function(player)
	local playername = player:get_player_name()
	if not minetest.get_modpath("hudbars") ~= nil then
		mana.hud_remove(playername)
	end
	mana.save(playername)
	mana.playerlist[playername] = nil
end)

minetest.register_on_shutdown(function()
	local players = minetest.get_connected_players()
	for v, player in ipairs(players) do
		local name = player:get_player_name()
		mana.save(name)
	end
end)

minetest.register_on_joinplayer(function(player)
	local playername = player:get_player_name()

	if not mana.playerlist[playername] then
		init_player(playername)
	end
end)


--[===[
	Mana regeneration
]===]

mana.regen_timer = 0

minetest.register_globalstep(function(dtime)
	mana.regen_timer = mana.regen_timer + dtime
	if mana.regen_timer >= mana.settings.regen_timer then
		local factor = math.floor(mana.regen_timer / mana.settings.regen_timer)
		local players = minetest.get_connected_players()
		for i=1, #players do
			local name = players[i]:get_player_name()

			local player_tab = mana.playerlist[name]

			if player_tab ~= nil then
				if players[i]:get_hp() > 0 then
					local plus = player_tab.regen * factor
					plus = plus + player_tab.remainder
					local plus_now = math.floor(plus)
					local floor = plus - plus_now
					if plus_now > 0 then
						mana.add_up_to(name, plus_now)
					else
						mana.subtract_up_to(name, math.abs(plus_now))
					end
					player_tab.remainder = floor

					for ident, fun in pairs(player_tab.tick_callbacks) do
						fun(ident, players[i], name)
					end
				end
			end
		end
		mana.regen_timer = mana.regen_timer % mana.settings.regen_timer
	end
end)

--[===[
	HUD functions
]===]

if minetest.get_modpath("hudbars") ~= nil then
	hb.register_hudbar("mana", 0xFFFFFF, S("Mana"), { bar = "mana_bar.png", icon = "mana_icon.png", bgicon = "mana_bgicon.png" }, 0, mana.settings.default_max, false)

	function mana.hud_update(playername)
		local player = minetest.get_player_by_name(playername)
		if player ~= nil then
			hb.change_hudbar(player, "mana", mana.get(playername), mana.getmax(playername))
		end
	end

	function mana.hud_remove(playername)
	end

else
	function mana.manastring(playername)
		return S("Mana: @1/@2", mana.get(playername), mana.getmax(playername))
	end

	function mana.hud_add(playername)
		local player = minetest.get_player_by_name(playername)
		local id = player:hud_add({
			hud_elem_type = "text",
			position = { x = 0.5, y=1 },
			text = mana.manastring(playername),
			scale = { x = 0, y = 0 },
			alignment = { x = 1, y = 0},
			direction = 1,
			number = 0xFFFFFF,
			offset = { x = -262, y = -103}
		})
		mana.playerlist[playername].hudid = id
		return id
	end

	function mana.hud_update(playername)
		local player = minetest.get_player_by_name(playername)
		player:hud_change(mana.playerlist[playername].hudid, "text", mana.manastring(playername))
	end

	function mana.hud_remove(playername)
		local player = minetest.get_player_by_name(playername)
		player:hud_remove(mana.playerlist[playername].hudid)
	end
end

--[===[
	Helper functions
]===]
mana.round = function(x)
	return math.ceil(math.floor(x+0.5))
end
